﻿using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace DepSoft.Mobile.WP7.FollwIt.Framework
{
    /// <summary>
    /// http://csainty.blogspot.com/2010/10/windows-phone-7images.html
    /// Assync download of Image through given URL
    /// 
    /// Possible other solution
    /// http://blogs.msdn.com/b/rohantha/archive/2010/09/12/silverlight-wp7-list-scroll-with-items-as-image-description-from-web-bing-image-search.aspx
    /// </summary>
    public static class ImageExtension
    {
        public static string GetSource(DependencyObject obj)
        {
            return (string)obj.GetValue(SourceProperty);
        }

        public static void SetSource(DependencyObject obj, string value)
        {
            obj.SetValue(SourceProperty, value);
        }

        // Using a DependencyProperty as the backing store for Source.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached("Source", typeof(string), typeof(ImageExtension), new PropertyMetadata(SourceChange));

        private static void SourceChange(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            Image imageControl = sender as Image;
            if (imageControl == null)
                return;
            string url = (string)e.NewValue as string;
            if (DesignerProperties.IsInDesignTool)
            {
                imageControl.Source = new BitmapImage(new Uri(url, UriKind.Absolute));
            }
            else
            {
                HttpWebRequest request = HttpWebRequest.CreateHttp(url);
                request.AllowReadStreamBuffering = true;
                request.BeginGetResponse(RequestComplete, new CallbackData { Request = request, ImageControl = imageControl });
            }
        }

        private static void RequestComplete(IAsyncResult result)
        {
            CallbackData data = (CallbackData)result.AsyncState;
            HttpWebResponse response = (HttpWebResponse)data.Request.EndGetResponse(result);
            data.ResponseStream = response.GetResponseStream();
            ((App)App.Current).RootFrame.Dispatcher.BeginInvoke(new Action<CallbackData>(x =>
            {
                BitmapImage imagesource = new BitmapImage();
                imagesource.SetSource(x.ResponseStream);
                x.ImageControl.Source = imagesource;
            }), data);
        }
    }

    public class CallbackData
    {
        public HttpWebRequest Request { get; set; }
        public Image ImageControl { get; set; }
        public Stream ResponseStream { get; set; }
    }
}